package runze.shiro.service;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import runze.shiro.dao.UserDao;
import runze.shiro.domain.User;

/**
 * @author wrzhxy@qq.com
 * @date 2017年12月28日
 */
@Transactional
@Service
public class UserService {
	
	public List<User> getAllUsers() {
		return (List<User>) userDao.findAll();
	}
	
	public User getCurrentUser() {
        final Integer currentUserId = (Integer) SecurityUtils.getSubject().getPrincipal();
        if( currentUserId != null ) {
            return getUser(currentUserId);
        } else {
            return null;
        }
    }
	
	public User getUser(Integer currentUserId) {
		return userDao.findOne(currentUserId);
	}
	public User getUser(String username) {
		return userDao.findByUsername(username);
	}

	public User createUser(User user) {
System.out.println("service create user");		
		return userDao.save(user);
	}
	
	public void updateUser(User user) {
		User one = userDao.findOne(user.getId());
		
		String username = user.getUsername();
		if (StringUtils.hasText(username)) one.setUsername(username);
		
		String password = user.getPassword();
		if (StringUtils.hasText(password)) one.setPassword(password);	// 加密两次？
		
		String email = user.getEmail();
		if (StringUtils.hasText(email)) one.setEmail(email);
//		userDao.
	}
	
	public void deleteUser(Integer id) {
//		userDao.findOne(id)
		userDao.delete(id);
	}
	
	@Autowired
	private UserDao userDao;
}
